<template>
  <div class="table-box">
    <ProTable
      ref="proTable"
      title="用户列表"
      rowKey="userId"
      :columns="columns"
      :request-api="getTableList"
      :init-param="initParam"
      :data-callback="dataCallback"
      v-if="btnsPurview && btnsPurview.query.isShow"
    >
      <!-- 表格 header 按钮 -->
      <template #tableHeader="scope">
        <el-button type="primary" :icon="CirclePlus" @click="openDrawer('新增')" v-if="btnsPurview && btnsPurview.add.isShow"
          >新增用户</el-button
        >
        <!-- <el-button type="primary" :icon="Download" plain @click="downloadFile">导出用户数据</el-button> -->
        <el-button
          type="danger"
          :icon="Delete"
          plain
          @click="batchDelete(scope.selectedListIds)"
          :disabled="!scope.isSelected"
          v-if="btnsPurview && btnsPurview.remove.isShow"
        >
          批量删除用户
        </el-button>
      </template>
      <!-- Expand -->
      <template #expand="scope">
        {{ scope.row }}
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button
          type="primary"
          link
          :icon="EditPen"
          :disabled="scope.row!.isDefault"
          @click="openDrawer('编辑', scope.row)"
          v-if="btnsPurview && btnsPurview.modify.isShow"
          >编辑</el-button
        >
        <el-button
          type="primary"
          link
          :icon="Refresh"
          @click="openDialog(scope.row)"
          v-if="btnsPurview && btnsPurview?.resetPsd?.isShow"
          >重置密码</el-button
        >
        <el-button
          type="primary"
          link
          :icon="Delete"
          :disabled="scope.row.isDefault"
          @click="_delete(scope.row)"
          v-if="btnsPurview && btnsPurview.remove.isShow"
          >删除</el-button
        >
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
    <ImportExcel ref="dialogRef" />
    <ResetPsdDialog ref="passwordRef" />
  </div>
</template>

<script setup lang="tsx" name="userInfo">
import { ref, reactive } from "vue";
import { User } from "@/api/interface";
import { ColumnProps } from "@/components/ProTable/interface";
import { useHandleData } from "@/hooks/useHandleData";
// import { useDownload } from "@/hooks/useDownload";
// import { ElMessageBox } from "element-plus";
import ProTable from "@/components/ProTable/index.vue";
import ImportExcel from "@/components/ImportExcel/index.vue";
import UserDrawer from "./components/UserDrawer.vue";
import ResetPsdDialog from "./components/ResetPsdDialog.vue";
import { CirclePlus, Delete, EditPen, /*Download,*/ Refresh } from "@element-plus/icons-vue";
import { getUserList, deleteUser, editUser, addUser, /*exportUserInfo,*/ changeUserStatus } from "@/api/modules/user";
import { useRoute } from "vue-router";
import { useUserStore } from "@/stores/modules/user";
const route = useRoute();
const userStore = useUserStore();
const btnsPurview = userStore.handlePurviewData[route.name as keyof typeof userStore.handlePurviewData];
// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref();
// 如果表格需要初始化请求参数，直接定义传给 ProTable(之后每次请求都会自动带上该参数，此参数更改之后也会一直带上，改变此参数会自动刷新表格数据)
const initParam = reactive({ type: 1 });

// dataCallback 是对于返回的表格数据做处理，如果你后台返回的数据不是 list && total && pageNum && pageSize 这些字段，那么你可以在这里进行处理成这些字段
// 或者直接去 hooks/useTable.ts 文件中把字段改为你后端对应的就行
const dataCallback = (data: any) => {
  return {
    list: data.userList,
    total: data.total,
    pageNum: data.pageNum,
    pageSize: data.pageSize
  };
};

// 如果你想在请求之前对当前请求参数做一些操作，可以自定义如下函数：params 为当前所有的请求参数（包括分页），最后返回请求列表接口
// 默认不做操作就直接在 ProTable 组件上绑定	:requestApi="getUserList"
const getTableList = (params: any) => {
  let newParams = JSON.parse(JSON.stringify(params));
  return getUserList(newParams);
};

// 过滤选择项
const selectable = (row: any) => {
  return !row.isDefault;
};

// 表格配置项
const columns: ColumnProps<User.ResUserList>[] = [
  { type: "selection", fixed: "left", width: 80, selectable },
  { type: "index", label: "序号", width: 80 },
  {
    prop: "userName",
    label: "姓名",
    search: { el: "input" },
    width: 120
  },
  {
    prop: "sex",
    label: "性别",
    width: 120
  },
  {
    prop: "jobNumber",
    label: "工号",
    width: 120
  },
  { prop: "userAccount", label: "登录用户名", search: { el: "input" }, width: 120 },
  {
    prop: "userType",
    label: "身份",
    render: scope => {
      let userTypeName = "";
      switch (scope.row.userType) {
        case "manager":
          userTypeName = "管理员";
          break;
        case "teacher":
          userTypeName = "老师";
          break;
        case "student":
          userTypeName = "学生";
          break;
        default:
          break;
      }
      return (
        <div>
          <span>{userTypeName}</span>
        </div>
      );
    },
    width: 120
  },
  {
    prop: "mobile",
    label: "电话号码",
    width: 120
  },
  {
    prop: "status",
    label: "用户状态",
    render: scope => {
      return (
        <>
          {
            <el-switch
              model-value={scope.row.status}
              active-value={1}
              inactive-value={2}
              onClick={() => {
                btnsPurview && btnsPurview["modifyStatus"]["isShow"] ? _changeStatus(scope.row) : "";
              }}
              disabled={scope.row.isDefault}
            />
          }
        </>
      );
    },
    width: 120
  },
  { prop: "operation", label: "操作", fixed: "right", width: 240 }
];

/**
 * 切换用户状态
 */
const _changeStatus = async (row: User.ResUserList) => {
  if (row.isDefault) {
    return false;
  }
  await useHandleData(
    changeUserStatus,
    { userList: [{ userId: row.userId }], status: row.status == 1 ? 2 : 1 },
    `切换【${row.userName}】用户状态`
  );
  proTable.value.getTableList();
};

// 删除用户信息
const _delete = async (params: User.ResUserList) => {
  await useHandleData(deleteUser, { userList: [{ userId: params.userId }] }, `删除【${params.userName}】用户`);
  proTable.value.getTableList();
};

// 批量删除用户信息
const batchDelete = async (selectedListIds: string[]) => {
  const userList = selectedListIds.map(value => {
    return { userId: value };
  });

  await useHandleData(deleteUser, { userList }, "删除所选用户信息");
  proTable.value.clearSelection();
  proTable.value.getTableList();
};
// // 导出用户列表
// const downloadFile = async () => {
//   ElMessageBox.confirm("确认导出用户数据?", "温馨提示", { type: "warning" }).then(() =>
//     useDownload(exportUserInfo, "用户列表", proTable.value.searchParam)
//   );
// };

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null);
const openDrawer = (title: string, row: Partial<User.ResUserList> = {}) => {
  const params = {
    title,
    isView: title === "查看",
    row: { ...row },
    api: title === "新增" ? addUser : title === "编辑" ? editUser : undefined,
    getTableList: proTable.value.getTableList,
    resetTableList: proTable.value.reset
  };

  drawerRef.value?.acceptParams(params);
};
const passwordRef = ref<InstanceType<typeof ResetPsdDialog> | null>(null);
const openDialog = (row: Partial<User.ResUserList> = {}) => {
  passwordRef.value?.openDialog(row.userId as string);
};
</script>
